<template>
  <div>
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        ref="formData"
        :model="form.val"
        :rules="form.rules"
        :label-col="form.labelCol"
        :wrapper-col="form.wrapperCol"
      >
        <a-form-model-item label="用户类型" prop="type">
          <a-select v-model="form.val.type" placeholder="请选择">
            <a-select-option
              v-for="(item, index) in typeOptions"
              :key="index"
              :value="index">
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="角色" prop="roleIds">
          <a-select v-model="form.val.roleIds" mode="multiple" placeholder="请选择">
            <a-select-option
              v-for="item in roleList"
              :key="item.id"
              :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="组织" prop="orgIds">
          <a-cascader
            v-model="form.val.orgIds"
            changeOnSelect
            :field-names="{ label: 'majorName', value: 'id', children: 'children' }"
            :options="orgOptions"
            placeholder="请选择"
          />
        </a-form-model-item>
        <a-form-model-item label="账号" prop="account">
          <a-input v-model="form.val.account" disabled placeholder="请输入" />
        </a-form-model-item>
        <!-- <template v-if="currentInfo.isAdd">
          <a-form-model-item label="密码" prop="password">
            <a-input-password v-model="form.val.password" placeholder="请输入" />
          </a-form-model-item>
          <a-form-model-item label="确认密码" prop="repassword">
            <a-input-password v-model="form.val.repassword" placeholder="请确认密码" />
          </a-form-model-item>
        </template> -->
        <a-form-model-item label="姓名" prop="name">
          <a-input v-model="form.val.name" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item label="手机号" prop="phone">
          <a-input v-model="form.val.phone" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item label="邮箱" prop="email">
          <a-input v-model="form.val.email" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item label="个人简介" prop="remark">
          <a-input v-model="form.val.remark" type="textarea" placeholder="请输入" />
        </a-form-model-item>
      </a-form-model>
    </a-spin>
    <a-form-model-item class="form-btn">
      <a-button @click="closeDetail(false)">取消</a-button>
      <a-button type="primary" :loading="form.confirmLoading" @click="onSubmit">确定</a-button>
    </a-form-model-item>
  </div>
</template>

<script>
import { getUserInfo, updateUserInfo, getRoleList, getOrgTree } from '@/api/system'
import { validPhone, validEmail } from '@/utils/validator'
import { listToTree } from '@/utils/common'

export default {
  props: {
    currentInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    // 校验手机号
    const phoneCheck = (rule, value, callback) => {
      if (!validPhone(value)) {
        callback(new Error('手机号格式不合法'))
        return false
      }
      callback()
    }
    // 校验邮箱
    const emailCheck = (rule, value, callback) => {
      if (!validEmail(value)) {
        callback(new Error('邮箱格式不合法'))
        return false
      }
      callback()
    }
    // 校验账号
    const accountCheck = (rule, value, callback) => {
      var isTrue = false
      var uname = value.trim()
      // 判断是否为空

      if (uname === '') {
        callback(new Error('账号不允许为空'))
      }

      // 判断是否有非法字符(除了中英文、数字、下划线以外的字符)
      var charReg = /[^\u4E00-\u9FA5\w]/
      var res = charReg.test(uname)
      // 如果res为真，表示有非法字符
      if (res) {
        callback(new Error('账号仅支持中英文、数字和下划线'))
      }

      // 经过上述判断后，说明都是合法的字符(中英文、下划线、数字)，接下来判断是否为纯数字
      // var numReg = /\D/
      // var res1 = numReg.test(uname)

      // 如果res为false，则表示出了数字以外无其他字符
      // if (!res1) {
      //   callback(new Error('账号不能为纯数字'))
      // }
      // 满足以上条件后，判断账号字符串的长度
      var len = 0 // 表示账号的长度
      for (var i = 0; i < uname.length; i++) {
        // 如果是中文，就+2；否则+1
        if (/[\u4E00-\u9FA5]/.test(uname[i])) {
          len += 2
        } else {
          len += 1
        }

        // 尽量避免执行过多的次数，一旦len超过14就不满足条件了
        if (len > 14) {
          break
        }
      }

      // 判断是否满足条件
      if (len > 14) {
        callback(new Error('账号不能超过7个汉字或14个字符'))
      } else {
        isTrue = true
      }
      if (isTrue) {
        callback()
      }
    }
    const passwordCheck = (rule, value, callback) => {
      // 判断这个字符串中有没有数字
      if (!/[0-9]/.test(value)) {
        return callback(new Error('必须包含数字'))
      }
      // 判断字符串中有没有字母
      if (!/[a-zA-Z]/.test(value)) {
        return callback(new Error('必须包含字母'))
      }
      // 判断字符串中有没有特殊符号
      if (!/[^0-9a-zA-Z]/.test(value)) {
        return callback(new Error('必须包含特殊符号'))
      }
      callback()
    }
    // 确认密码验证
    const repasswordCheck = (rule, value, callback) => {
      const password = this.form.val.password
      if (value && password && value.trim() !== password.trim()) {
        return callback(new Error('两次密码不一致'))
      }
      callback()
    }

    return {
      spinning: false,
      roleList: [],
      orgOptions: [],
      typeOptions: ['学生', '老师', '平台管理员'],
      form: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        },
        confirmLoading: false,
        val: {},
        rules: {
          type: [{ required: true, message: '用户类型不可为空', trigger: 'change' }],
          roleIds: [{ required: true, message: '角色不可为空', trigger: 'change' }],
          orgIds: [{ required: true, message: '组织不可为空', trigger: 'change' }],
          account: [
            { required: true, message: '账号不可为空', trigger: 'blur' },
            { validator: accountCheck, trigger: 'blur' }
          ],
          password: [
            { required: true, message: '密码不可为空', trigger: 'blur' },
            { validator: passwordCheck, trigger: 'blur' }
          ],
          repassword: [
            { required: true, message: '确定密码不可为空', trigger: 'blur' },
            { validator: repasswordCheck, trigger: 'blur' }
          ],
          name: [{ required: true, message: '姓名不可为空', trigger: 'blur' }],
          phone: [
            { required: true, message: '手机号不可为空', trigger: 'blur' },
            { validator: phoneCheck, trigger: 'blur' }
          ],
          email: [
            { required: true, message: '邮箱不可为空', trigger: 'blur' },
            { validator: emailCheck, trigger: 'blur' }
          ]
        }
      }
    }
  },
  watch: {
    'currentInfo.id': {
      handler: 'resetForm',
      immediate: true
    }
  },
  created () {
    this.getRoleOptions()
    this.getOrgTreeList()
  },
  methods: {
    // 重构表单内容
    resetForm (val) {
      this.form.confirmLoading = false
      this.$nextTick(() => { // 清除表单验证结果
        this.$refs.formData.clearValidate()
      })
      this.getInfo(val)
    },
    // 获取角色列表
    getRoleOptions () {
      getRoleList().then(res => {
        this.roleList = res.content || []
      })
    },
    // 获取组织树形结构
    getOrgTreeList () {
      getOrgTree().then(res => {
        const orgList = []
        listToTree(res.content || [], orgList, 1)
        this.orgOptions = orgList
      })
    },
    // 获取详情
    getInfo (id) {
      this.spinning = true
      getUserInfo({ id }).then(res => {
        const { account, name, phone, email, type, roleIds, remark, organizationIds } = res.content || {}
        this.form.val = {
          id,
          account,
          name,
          phone,
          email,
          remark,
          type: type === null ? undefined : type,
          roleIds: this.getIds(roleIds),
          orgIds: this.getIds(organizationIds)
        }
      }).finally(res => {
        this.spinning = false
      })
    },
    // 获取用户角色
    getRoleIds (list) {
      if (!list) {
        return []
      }
      return list.map(item => item.id)
    },
    // 获取组织的父 ids
    getIds (ids) {
      if (!ids) {
        return undefined
      }
      const idAll = ids.split(',')
      // idAll.pop()
      return idAll.map(Number)
    },
    // 关闭弹出框
    closeDetail (val = false) {
      this.form.confirmLoading = false
      this.$emit('emitToParent', val)
    },
    // 提交表单信息
    onSubmit (formName) {
      this.$refs.formData.validate(valid => {
        if (valid) {
          this.form.confirmLoading = true
          const { orgIds, roleIds } = this.form.val
          const params = {
            ...this.form.val,
            roleIds: roleIds && roleIds.join(','),
            organizationId: orgIds && orgIds.length ? orgIds[orgIds.length - 1] : undefined
          }
          console.log(this.currentInfo)
          if (this.currentInfo.status === 0) {
            params.status = 1
          }
          delete params.orgIds
          this.updateInfo(params)
        }
      })
    },
    // 修改表单信息接口相应
    updateInfo (params) {
      updateUserInfo(params).then(response => {
        this.$message.success((params.id ? '修改' : '新增') + '成功！')
        this.closeDetail(true)
      }).finally(() => {
        this.form.confirmLoading = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
  .register-button {
    width: 50%;
    margin-left:22px;
  }
  .login {
    float: right;
    line-height: 40px;
  }
</style>
